package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.behavior.mapper.ApReadBehaviorMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.ApReadBehaviorService;
import com.usian.model.behavior.dtos.ReadBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApReadBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Log4j2
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements ApReadBehaviorService {
    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;


    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        //1.参数校验
        if (dto == null || dto.getArticleId() ==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry entry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (entry == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //3.保存或者更新阅读的行为
        ApReadBehavior one = getOne(Wrappers.<ApReadBehavior>lambdaQuery().eq(ApReadBehavior::getEntryId, entry.getId()).eq(ApReadBehavior::getArticleId, dto.getArticleId()));

        //如果行为（实体）不存在
        if (one == null) {
            one = new ApReadBehavior();
            one.setCount(dto.getCount());
            one.setArticleId(dto.getArticleId());
            one.setPercentage(dto.getPercentage());
            one.setEntryId(entry.getId());
            one.setLoadDuration(dto.getLoadDuration());
            one.setReadDuration(dto.getReadDuration());
            one.setCreatedTime(new Date());
            save(one);
        }else {
            //如果阅读行为存在（有阅读次数），则重新修改阅读行为的次数
            one.setUpdatedTime(new Date());
            one.setCount((short)(one.getCount()+1));
            updateById(one);
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}
